// import React from 'react';
import {withRouter} from 'react-router-dom';
import {message} from 'antd';
import {UserCookies} from '@assets/config/global_config.js';

message.config({
    top: 100,
    maxCount: 3,
});

const combineObj = function () {
    let target = {};
    for (let i = 1; i < arguments.length; i++) {
        let source = arguments[i];
        for (let key in source) {
            if (Object.prototype.hasOwnProperty.call(source, key)) {
                target[key] = source[key];
            }
        }
    }
    return target;
};

/**
 * @param options
 * @param ccb => onClose
 * @param afcb => after close
 */

const tooltip = (options, ccb = null, afcb = null) => {
    let {level, content, duration} = options;
    message[level](content, duration || 2, ccb || '').then(afcb || '');
};

/**
 * 获取cookie
 * */
const getCookie = (cname) => {
    let name = cname + "=";
    let ca = document.cookie.split(';');
    for (let i = 0; i < ca.length; i++) {
        let c = ca[i].trim();
        if (c.indexOf(name) === 0) return c.substring(name.length, c.length);
    }
    return "";
};

const getCookies = (cnames = []) => {
    let obj = {};
    cnames.map(item => {
        obj[item] = getCookie(item);
        return false;
    });
    return obj;
};

/**
 * 判断cookie是否失效
 * */
const judgeCookies = (cookies) => {
    let isValid = false;
    let cs = getCookies(cookies);
    Object.keys(cs).map(item => {
        void(!cs[item] ? isValid = true : 0);
        return false;
    });
    return isValid;
};

/*
 * 重新做登录
 * */
const reLogin = () => {
    let hash = window.location.hash.replace('#', '');
    let origin = window.location.origin;
    let url = `${origin}/#/login`;
    // 当前在首页 就直接到登录页面 如果是别的页面 则登录后在回到上次退出的页面
    void(hash === '#/layout/home' ? 0 : url += `?redirect=${encodeURIComponent(hash)}`);
    window.location.href = url;
};

/**
 * urlSearchObj
 * 获取url中携带的search参数
 * searchItem需要的某一项
 * 如果为空 返回的是search参数组成的对象
 */
const urlSearchObj = (urlSearch='', searchItem='') => {
    if (!!!urlSearch) {
        return '';
    }
    let searchArr = urlSearch.replace('?', '').split('&');
    let searchObj = {};
    searchArr.map(item => {
        let searchItemArr = item.split('='),
            prototype = searchItemArr[0],
            value = searchItemArr[1];
        searchObj[prototype] = value;
        return null;
    });
    return !!!searchItem ? searchObj : (searchObj[searchItem] === undefined ? '' : searchObj[searchItem]);
};


export default {

    bindRouteProps: (component) => {
        return withRouter(component);
    },

    seekPath(obj) {
        // 用户跳转路由之前判断登录是否过期
        let userPast = judgeCookies(UserCookies);
        if (userPast && (obj !== '/login')) {
            tooltip({level: 'error', content: '登录过期，请重新登录'});
            reLogin();
            return false;
        }

        let pathname = this.props.location.pathname;
        let isSome = !!obj.pathname ? obj.pathname === pathname : obj === pathname;
        if (isSome)
            return false;
        this.props.history.push(obj);
    },
    /**
     * @param obj
     */
    setCallback(obj = {}) {
        let cbs = Array.prototype.slice.call(arguments).slice(1);
        this.setState(obj, () => {
            if (!cbs.length)
                return false;
            cbs.map(cb => Object.prototype.toString.call(cb) === '[object Function]' && cb.call(this))
            return false;
        })
    },

    objectAssign: Object.assign || combineObj,

    /**
     * 数字每三位断开
     * */
    formatNumber: (num = '') => {
        if (Object.prototype.toString.call(num) !== '[object Number]')
            return '---';
        return parseFloat(num).toLocaleString();
    },

    // antd message
    tooltip,

    /**
     * 数组除去指定项
     */
    delOption: (array = [], option = '') => {
        let newArr = [];
        for (let i = 0; i < array.length; i++) {
            let curItem = array[i];
            if (curItem !== option) {
                newArr.push(curItem);
            }
        }
        return newArr;
    },

    /**
     设置cookies
     */
    setCookie: (cookies = {}, exdays = 1) => {
        let keys = Object.keys(cookies);
        keys.map((item, index) => {
            let d = new Date();
            d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000 + (index * 1000)));
            let expires = "expires=" + d.toGMTString();
            document.cookie = item + "=" + cookies[item] + "; " + expires;
            return false;
        });
        return false;
    },


    //取cookie
    getCookie,
    getCookies,

    /**
     * dom 监听
     * style中 width 与 height 发生改变
     * */
    mutation(_this, options = {}, cb = null) {
        let MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver;
        let targetNode = document.querySelector(options.selector || '');
        _this.observer = new MutationObserver(cb && cb.bind(_this));
        _this.observer.observe(targetNode, options.config || {});
    },

    /**
     * 获取元素的属性
     * */
    getStyle(dom, property = '') {
        return !property ? window.getComputedStyle(dom) : window.getComputedStyle(dom)[property];
    },

    /**
     * 默认降序
     * dis => 1 升序 0 降序
     * */
    arrLargest(arr = [], property = '', dis = 0) {
        if (!arr || !arr.length || Object.prototype.toString.call(arr) !== "[object Array]")
            return null;
        if (!property) {
            arr.sort()
        } else (
            arr.sort((a, b) => {
                return !dis ? b[property] - a[property] : a[property] - b[property];
            })
        );

        return {
            largest: !property ? (!dis ? arr[0] : arr[arr.length - 1]) : (!dis ? arr[0][property] : arr[arr.length - 1][property]),
            mini: !property ? (!dis ? arr[arr.length - 1] : arr[0]) : (!dis ? arr[arr.length - 1][property] : arr[0][property]),
            result: arr
        };
    },

    //重新做登录
    reLogin,
    // 判断cookies 是否存在
    judgeCookies,

    // 获取url中的某一个
    urlSearchObj
}